package com.tevintao.marketingsystem.task;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.TaskLogicService;
import com.tevintao.marketingsystem.services.ViewOperation;
import com.tevintao.marketingsystem.xposted.HookWindowManagerGlobal;
import com.tevintao.marketingsystem.xposted.WxTaskManger;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 基础任务处理，主要用来处理
 * 登录过期的情况
 * 帐号被封,上报
 */
public class BaseTaskProcess extends SetTaskExtra {


    private static BaseTaskProcess ourInstance = new BaseTaskProcess();

    public static BaseTaskProcess getInstance() {
        return ourInstance;
    }

    private BaseTaskProcess() {
    }

    public static Set<String> mInternationalCode = new HashSet<>();

    static {
        mInternationalCode.add("971");
        mInternationalCode.add("95");
    }

    @SuppressWarnings("ResourceType")
    @Override
    public boolean processView(String contextName, View v) {
        if (WxUiViewConfig.haveLogin(contextName, v)) {
//            LogManager.getInstance().logInfo("已经登录");
            if (WxTaskProcess.DEBUG_MODEL) {
                Object back = getExtra(WxTaskManger.KEY_NEED_BACK_2_MAIN);
//                LogManager.getInstance().logInfo("back = " + back);
                if (back instanceof Boolean) {
                    boolean need = (boolean) back;
                    if (need) {
                        if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
                            View chatViewGroupView = v.findViewById(WxUiViewConfig.CHAT_VIEW_GROUP_VIEW);
                            if (null != chatViewGroupView && chatViewGroupView.getVisibility() == View.VISIBLE) {
                                LogManager.getInstance().logInfo("聊天界面已经打开");
                                Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
                                Bundle bundle = new Bundle();
                                bundle.putInt(TaskLogicService.KEY_INPUT_KEY, TaskLogicService.INPUT_TYPE_BACK);
                                intent.putExtras(bundle);
                                v.getContext().sendBroadcast(intent);
                            } else {
                                v.getContext().sendBroadcast(new Intent(WxTaskManger.ACTION_HAVE_BACK_FINISH));
                            }
                        } else {
                            Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
                            Bundle bundle = new Bundle();
                            bundle.putInt(TaskLogicService.KEY_INPUT_KEY, TaskLogicService.INPUT_TYPE_BACK);
                            intent.putExtras(bundle);
                            v.getContext().sendBroadcast(intent);
                        }
                        LogManager.getInstance().logInfo("需要返回");
                        return true;
                    }
                }
            } else {
                if (WxTaskManger.getInstance().isNeed2Main()) {
                    if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
                        View chatViewGroupView = v.findViewById(WxUiViewConfig.CHAT_VIEW_GROUP_VIEW);
                        if (null != chatViewGroupView && chatViewGroupView.getVisibility() == View.VISIBLE) {
                            LogManager.getInstance().logInfo("聊天界面已经打开");
                            Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
                            Bundle bundle = new Bundle();
                            bundle.putInt(TaskLogicService.KEY_INPUT_KEY, TaskLogicService.INPUT_TYPE_BACK);
                            intent.putExtras(bundle);
                            v.getContext().sendBroadcast(intent);
                        } else {
                            WxTaskManger.getInstance().setNeed2Main(false);
                        }
                    } else {
                        Intent intent = new Intent(TaskLogicService.ACTION_KEY_RECEIVER);
                        Bundle bundle = new Bundle();
                        bundle.putInt(TaskLogicService.KEY_INPUT_KEY, TaskLogicService.INPUT_TYPE_BACK);
                        intent.putExtras(bundle);
                        v.getContext().sendBroadcast(intent);
                        LogManager.getInstance().logInfo("需要返回");
                    }
                    return true;
                }
            }
        } /*else {
//            LogManager.getInstance().logInfo("未登录");
        }*/
        if (WxUiViewConfig.DIALOG_CLASS.equals(contextName)) {
//            JSONObject joTree = HookWindowManagerGlobal.GetViewJsonTree((ViewGroup) v, -1);
//            HookWindowManagerGlobal.printViewTreeJson(joTree, 0);
            WxUiViewConfig.printViewGroup((ViewGroup) v);
            View info = v.findViewById(WxUiViewConfig.DIALOG_INFO_TEXT);
            if (null != info) {
                TextView tv = (TextView) info;
                String promptMessage = tv.getText().toString();
                LogManager.getInstance().logInfo("promptMessage = " + promptMessage);
                if (promptMessage.contains("封号")) {
                    LogManager.getInstance().logError("错误信息包含封号 关键字");
                    taskError(v.getContext(), WxTaskManger.TASK_STATE_ACCOUNT_BAN, promptMessage);
                    return true;
                } else if (promptMessage.contains("帐号或密码错误")) {
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_PASSWORD_ERROR, promptMessage);
                    return true;
                } else if (promptMessage.contains("是否取消安装")) {
                    //取消更新
                    LogManager.getInstance().logInfo("点击即可取消更新");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                } else if (promptMessage.startsWith("你当前的网络可能存在问题")) {
                    LogManager.getInstance().logError("网络存在问题，点击取消。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                } else if (promptMessage.startsWith("当前帐号于")) {
                    LogManager.getInstance().logError("挤下线");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                } else if (promptMessage.startsWith("登录过期，请你重新登录。")) {
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                } else if (promptMessage.startsWith("你的帐户信息已过期")) {
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                }  else if (promptMessage.startsWith("你的微信帐号于")) {
                    LogManager.getInstance().logInfo("被挤下线");
                    taskError(v.getContext(), WxTaskManger.TASK_STATE_TIME_OUT, promptMessage);
                    return true;
                } else if (promptMessage.startsWith("登录错误，请重新登录。")) {
                    LogManager.getInstance().logError("发现登录错误，请重新登录");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                } else if (promptMessage.startsWith("操作过于频繁")) {
                    LogManager.getInstance().logError("操作过于频繁");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_FIND_FRIEND_ERROR, "需要手机验证");
                } else if(promptMessage.startsWith("该帐号长期未登录，为保护帐号安全")) {
                    LogManager.getInstance().logError(" 该帐号长期未登录，为保护帐号安全，系统将其自动置为保护状态。点击确定按钮可立即激活帐号解除保护状态。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_PHONE_VERIFICATION, "需要手机验证");
                } else  if (promptMessage.startsWith("该微信帐号因批量或者使用非法软件注册被执行封号可自助解封处罚")) {
//                    该微信帐号因批量或者使用非法软件注册被执行封号可自助解封处罚，如果希望继续正常使用微信，请轻触“确定”申请解封。
                    LogManager.getInstance().logError("该微信帐号因批量或者使用非法软件注册被执行封号可自助解封处罚，如果希望继续正常使用微信，请轻触“确定”申请解封。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_STATE_ACCOUNT_BAN, "该微信帐号因批量或者使用非法软件注册被执行封号可自助解封处罚，如果希望继续正常使用微信，请轻触“确定”申请解封。");
                }else if(promptMessage.startsWith("该微信帐号因登录环境异常，已被限制登录。")) {
//                    该微信帐号因登录环境异常，已被限制登录。轻触“确定”可申请激活。
                    LogManager.getInstance().logError("该微信帐号因登录环境异常，已被限制登录。轻触“确定”可申请激活。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_PHONE_VERIFICATION, "该微信帐号因登录环境异常，已被限制登录。轻触“确定”可申请激活。");
                }else if (promptMessage.startsWith("系统检测到你的帐号有异常，已被限制登录。")) {
                    LogManager.getInstance().logError("系统检测到你的帐号有异常，已被限制登录。轻触“确定”可申请激活。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_PHONE_VERIFICATION, "系统检测到你的帐号有异常，已被限制登录。轻触“确定”可申请激活。");
                } else if (promptMessage.startsWith("此微信帐号因长期没有使用，已被回收")) {
//                    此微信帐号因长期没有使用，已被回收。如需使用微信业务，可重新注册微信帐号。
                    LogManager.getInstance().logError("此微信帐号因长期没有使用，已被回收。如需使用微信业务，可重新注册微信帐号。");
                    View cancel = v.findViewById(WxUiViewConfig.DIALOG_INFO_OK);
                    if (null != cancel) {
                        ViewOperation.clickView(cancel);
                    }
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_ACCOUNT_PAST, "此微信帐号因长期没有使用，已被回收。如需使用微信业务，可重新注册微信帐号。");
                }
            }
        } else if (WxUiViewConfig.VIEW_SECURITY.equals(contextName)) {
            taskError(v.getContext(), WxTaskManger.TASK_SATE_PHONE_VERIFICATION, "需要手机验证");
        } else if (WxUiViewConfig.MAIN_LAUNCH.equals(contextName)) {
            View view = v.findViewById(WxUiViewConfig.FIRST_LOGIN_BUTTON);
            if (null != view) {
                ViewOperation.clickView(view);
            }
        } else if (WxUiViewConfig.PHONE_LOGIN_VIEW.equals(contextName)) {
            Object userNameObj = getExtra(WxUiViewConfig.KEY_USER_NAME);
            if (null == userNameObj) {
                LogManager.getInstance().logError("null == userNameObj");
                taskError(v.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "用户名获取失败");
                return true;
            } else {
                String userName = userNameObj.toString();
                String code = getCode(userName);
                LogManager.getInstance().logInfo("code = " + code);
                if (!TextUtils.isEmpty(code)) {
                    userName = userName.substring(code.length());
                    View codeEdit = v.findViewById(WxUiViewConfig.FIRST_LOGIN_INTERNATIONAL_CODE_EDIT_TEXT);
                    if (null != codeEdit) {
                        ViewOperation.setText(codeEdit, code);
                    } else {
                        taskError(v.getContext(), WxTaskManger.TASK_SATE_NOT_FIND_VIEW, "获取国际区号输入框失败 id = FIRST_LOGIN_INTERNATIONAL_CODE_EDIT_TEXT");
                        return true;
                    }
                }
                View userNameEdit = v.findViewById(WxUiViewConfig.FIRST_LOGIN_PHONE_EDIT_TEXT);
                if (null != userNameEdit) {
                    ViewOperation.setText(userNameEdit, userName);
                } else {
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_NOT_FIND_VIEW, "获取用户名输入框失败 id = FIRST_LOGIN_PHONE_EDIT_TEXT");
                    return true;
                }
            }

            Object passwordObj = getExtra(WxUiViewConfig.KEY_PASSWORD);
            if (null == passwordObj) {
                taskError(v.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "密码获取失败");
                return true;
            } else {
                String password = passwordObj.toString();
                View passwordEdit = v.findViewById(WxUiViewConfig.FIRST_LOGIN_PASSWORD_EDIT_TEXT);
                if (null != passwordEdit) {
                    ViewOperation.setText(passwordEdit, password);
                } else {
                    taskError(v.getContext(), WxTaskManger.TASK_SATE_NOT_FIND_VIEW, "获取密码输入框失败  id = FIRST_LOGIN_PASSWORD_EDIT_TEXT");
                    return true;
                }
            }

            View loginButton = v.findViewById(WxUiViewConfig.FIRST_LOGIN_LOGIN_BUTTON);
            if (null != loginButton) {
                ViewOperation.clickView(loginButton);
            } else {
                taskError(v.getContext(), WxTaskManger.TASK_SATE_NOT_FIND_VIEW, "获取登录按钮失败 id = FIRST_LOGIN_LOGIN_BUTTON");
                return true;
            }

        } else if (WxUiViewConfig.UPDATE_VERSION.equals(contextName)) {
            LogManager.getInstance().logInfo("WxUiViewConfig.UPDATE_VERSION");
            List<View> views = HookWindowManagerGlobal.getInstance().getViews();
            for (View vv : views) {
                Context context = vv.getContext();
                LogManager.getInstance().logInfo("context = " + context);
                if (null != context) {
                    String dialogName = context.getClass().getName();
                    LogManager.getInstance().logError("null != vv.getContext() dialogName = " + dialogName);
//                    JSONObject joTree = HookWindowManagerGlobal.GetViewJsonTree((ViewGroup) vv, -1);
//                    HookWindowManagerGlobal.printViewTreeJson(joTree, 0);
                    if (WxUiViewConfig.DIALOG_CLASS.equals(dialogName)) {
                        View info = vv.findViewById(WxUiViewConfig.DIALOG_INFO_TEXT);
                        if (null != info) {
                            TextView tv = (TextView) info;
                            String promptMessage = tv.getText().toString();
                            LogManager.getInstance().logInfo("UPDATE_VERSION promptMessage = " + promptMessage);
                            if (promptMessage.contains("微信 v")) { //更新
                                View cancel = vv.findViewById(WxUiViewConfig.DIALOG_INFO_CANCEL);
                                LogManager.getInstance().logInfo("cancel = " + cancel);
                                if (null != cancel) {
                                    ViewOperation.doClickListener(cancel);
                                }
                            }
                        }
                    }
                }
            }
        } else if (WxUiViewConfig.VIEW_CANCELLATION_VIEW.equals(contextName)) {
            LogManager.getInstance().logInfo("注销");
            taskError(v.getContext(), WxTaskManger.TASK_STATE_ACCOUNT_BAN, "注销页面");
        } else if (WxUiViewConfig.VIEW_LOGIN_AGAIN.equals(contextName)) {
            LogManager.getInstance().logInfo("contextName = " + WxUiViewConfig.VIEW_LOGIN_AGAIN);
            View passwordView = v.findViewById(WxUiViewConfig.ID_LOGIN_AGAIN_PASSWORD);
            if (null != passwordView) {
                EditText editText = (EditText) passwordView;
                String content = editText.getText().toString();
                LogManager.getInstance().logInfo("密码输入狂 " + content);
                if (TextUtils.isEmpty(content)) {
                    Object passwordObj = getExtra(WxUiViewConfig.KEY_PASSWORD);
                    if (null == passwordObj) {
                        taskError(v.getContext(), WxTaskManger.TASK_SATE_EXTRA_ERROR, "密码获取失败");
                        return true;
                    } else {
                        ViewOperation.setText(editText, passwordObj.toString());
                    }
                } else {
                    View loginView = v.findViewById(WxUiViewConfig.ID_LOGIN_AGAIN_LOGIN);
                    ViewOperation.clickView(loginView);
                }
            }
//            WxUiViewConfig.printViewGroup((ViewGroup) v);
        }
        return false;
    }

    private String getCode(String userName) {
        for (String code : mInternationalCode) {
            if (userName.startsWith(code)) {
                return code;
            }
        }
        return null;
    }
}
